/**
 * electron 主文件
 */
import { join } from "path";
import { app, BrowserWindow, ipcMain, Menu } from "electron";
import dotenv from "dotenv";
import { toMaxSize, toMiniSize } from "@main/directive";
import { createSubWin } from "./subWin";

dotenv.config({ path: join(__dirname, "../../.env") });

let win: BrowserWindow;

export const URL = app.isPackaged
  ? `file://${join(__dirname, "../render/index.html#")}` // vite 构建后的静态文件地址
  : `http://localhost:${process.env.PORT}#`; // vite 启动的服务器地址

function createWin() {
  // 创建浏览器窗口
  win = new BrowserWindow({
    width: 1024,
    height: 768,
    frame: false,
    // useContentSize: false,
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      webSecurity: false,
    },
  });
  win.webContents.toggleDevTools();
  win?.loadURL(URL + "/login");
}

app.whenReady().then(createWin);

// app.commandLine.appendSwitch("disable-features", "OutOfBlinkCors");
app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

try {
  require("electron-reloader")(module);
} catch {}

//order
ipcMain.on("closeMainWindow", () => {
  win.destroy();
});
ipcMain.on("toMinMainWin", () => {
  win && toMiniSize(win);
});
ipcMain.on("toMaxMainWin", () => {
  win && toMaxSize(win);
});
//subWin order
let subWin: BrowserWindow | null;
ipcMain.on("creatSubWin", () => {
  if (typeof subWin == "undefined" || subWin == null) {
    subWin = createSubWin(URL);
  }
});

ipcMain.on("closeSubWin", () => {
  if (subWin != null) {
    subWin.destroy();
  }
  subWin = null;
});
ipcMain.on("toMinSubWin", () => {
  subWin && toMiniSize(subWin);
});
ipcMain.on("toMaxSubWin", () => {
  subWin && toMaxSize(subWin);
});
